import Web3 from 'web3';
import { promises as fs } from 'fs';

const jsonData = await fs.readFile('./build/contracts/L1Bridge.json', 'utf-8');
const bridgeJson = JSON.parse(jsonData);
const bridgeAbi = bridgeJson.abi;
console.log(bridgeAbi);

// 配置参数
// account1

const USER_ADDRESS = '0xa659f022cb8d0Df682C327d2f16B6f2f41AD2aeA'; // 你的钱包地址
const PRIVATE_KEY = '0x7fd651a63dcca634d0b527bde1b96f1d2ee246af361f03f951723db27e24e54c'; // 你的钱包私钥

const RPC_URL = 'http://[::1]:8545'; // 你的以太坊节点RPC URL
const BRIDGE_CONTRACT_ADDRESS = '0xFfE0F18fa5C2A31ab1a710309990a9989d75EC94'; // L1Bridge 合约地址


const TOKEN_CONTRACT_ADDRESS = '0x43F0FFCA27B26dCfA02fce8cA5D97F2F85CbF3fa'; // ERC20 代币合约地址

// Web3 设置
const web3 = new Web3(RPC_URL);

// 后续的 Web3 合约和交易操作
console.log('Web3 已成功连接:', web3.currentProvider.host);

// 代币 ABI 和 L1Bridge 合约 ABI
// const bridgeAbi = [
//     { "constant": false, "inputs": [{ "name": "amount", "type": "uint256" }], "name": "deposit", "outputs": [], "type": "function" },
//     { "anonymous": false, "inputs": [{ "indexed": true, "name": "user", "type": "address" }, { "indexed": false, "name": "amount", "type": "uint256" }, { "indexed": false, "name": "timestamp", "type": "uint256" }], "name": "Deposit", "type": "event" }
// ];

const erc20Abi = [
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }], "name": "balanceOf", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" },
    { "constant": false, "inputs": [{ "name": "spender", "type": "address" }, { "name": "amount", "type": "uint256" }], "name": "approve", "outputs": [{ "name": "", "type": "bool" }], "type": "function" },
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }, { "name": "spender", "type": "address" }], "name": "allowance", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" }
];

async function main() {
    // 创建钱包签名者
    const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
    web3.eth.accounts.wallet.add(account);
    web3.eth.defaultAccount = account.address;

    // 创建 ERC20 代币合约实例
    const tokenContract = new web3.eth.Contract(erc20Abi, TOKEN_CONTRACT_ADDRESS);

    // 获取用户余额
    //const balance = await tokenContract.methods.balanceOf(USER_ADDRESS).call();
    //console.log(`当前余额: ${web3.utils.fromWei(balance, 'ether')} Tokens`);

    // 设置存款金额（例如 10 个代币）
    const depositAmount = web3.utils.toWei('300.0', 'ether'); // 存入 10 TOKEN

    // 检查是否已批准足够的代币给桥合约
    const allowance = await tokenContract.methods.allowance(USER_ADDRESS, BRIDGE_CONTRACT_ADDRESS).call();
    if (parseInt(allowance) < parseInt(depositAmount)) {
        console.log("批准代币给桥合约...");
        const approveTx = tokenContract.methods.approve(BRIDGE_CONTRACT_ADDRESS, depositAmount);
        const approveSignedTx = await web3.eth.sendTransaction({
            from: USER_ADDRESS,
            to: TOKEN_CONTRACT_ADDRESS,
            data: approveTx.encodeABI(),
            gas: 200000,
        });
        console.log("批准已完成。交易哈希:", approveSignedTx.transactionHash);
    } else {
        console.log("已批准足够的代币给桥合约。");
    }

    // 创建 L1Bridge 合约实例
    const bridgeContract = new web3.eth.Contract(bridgeAbi, BRIDGE_CONTRACT_ADDRESS);

    // 调用 setLimit 函数
    console.log(`正在设置存款限制为 ${web3.utils.fromWei(depositAmount, 'ether')} Tokens...`);
    const setLimitTx = bridgeContract.methods.setLimit(depositAmount);
    const signedSetLimitTx = await web3.eth.sendTransaction({
        from: USER_ADDRESS,
        to: BRIDGE_CONTRACT_ADDRESS,    
        data: setLimitTx.encodeABI(),
        gas: 20000000,
    });
    console.log("设置限制已完成。交易哈希:", signedSetLimitTx.transactionHash);


}

main().catch(error => {
    console.error("发生错误:", error);
    process.exit(1);
});
